﻿namespace Hidistro.ControlPanel.Sales
{
    using Hidistro.ControlPanel.Store;
    using Hidistro.Core.Entities;
    using Hidistro.Entities.Commodities;
    using Hidistro.Entities.Members;
    using Hidistro.Entities.Orders;
    using Hidistro.Entities.Promotions;
    using Hidistro.Entities.Store;
    using Hidistro.Membership.Context;
    using Hidistro.Membership.Core;
    using Hidistro.Membership.Core.Enums;
    using Hidistro.SqlDal;
    using Hidistro.SqlDal.Commodities;
    using Hidistro.SqlDal.Members;
    using Hidistro.SqlDal.Orders;
    using Microsoft.Practices.EnterpriseLibrary.Data;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Globalization;
    using System.Linq;
    using System.Runtime.InteropServices;

    public static class OrderHelper
    {
        public static bool AddOrderGift(OrderInfo order, GiftInfo giftinfo, int quantity, int promotype)
        {
            bool flag;
            ManagerHelper.CheckPrivilege(Privilege.EditOrders);
            using (DbConnection connection = DatabaseFactory.CreateDatabase().CreateConnection())
            {
                connection.Open();
                DbTransaction dbTran = connection.BeginTransaction();
                try
                {
                    OrderGiftInfo item = new OrderGiftInfo {
                        OrderId = order.OrderId,
                        Quantity = quantity,
                        GiftName = giftinfo.Name
                    };
                    decimal costPrice = item.CostPrice;
                    item.CostPrice = Convert.ToDecimal(giftinfo.CostPrice);
                    item.GiftId = giftinfo.GiftId;
                    item.ThumbnailsUrl = giftinfo.ThumbnailUrl40;
                    item.PromoteType = promotype;
                    bool flag2 = false;
                    foreach (OrderGiftInfo info2 in order.Gifts)
                    {
                        if (giftinfo.GiftId == info2.GiftId)
                        {
                            flag2 = true;
                            info2.Quantity = quantity;
                            info2.PromoteType = promotype;
                            break;
                        }
                    }
                    if (!flag2)
                    {
                        order.Gifts.Add(item);
                    }
                    if (!new OrderGiftDao().AddOrderGift(order.OrderId, item, quantity, dbTran))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    if (!new OrderDao().UpdateOrder(order, dbTran))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    dbTran.Commit();
                    flag = true;
                }
                catch
                {
                    dbTran.Rollback();
                    flag = false;
                }
                finally
                {
                    connection.Close();
                }
            }
            if (flag)
            {
                EventLogs.WriteOperationLog(Privilege.EditOrders, string.Format(CultureInfo.InvariantCulture, "成功的为订单号为\"{0}\"的订单添加了礼品", new object[] { order.OrderId }));
            }
            return flag;
        }

        public static bool CheckRefund(OrderInfo order, string Operator, string adminRemark, int refundType, bool accept)
        {
            ManagerHelper.CheckPrivilege(Privilege.OrderRefundApply);
            if (order.OrderStatus != OrderStatus.ApplyForRefund)
            {
                return false;
            }
            RefundDao dao = new RefundDao();
            bool flag = dao.CheckRefund(order, Operator, adminRemark, refundType, accept);
            if (flag)
            {
                if (accept)
                {
                    IUser user = Users.GetUser(order.UserId, false);
                    if ((user != null) && (user.UserRole == UserRole.Member))
                    {
                        ReducedPoint(order, user as Member);
                        ReduceDeduct(order.OrderId, order.GetTotal(), user as Member);
                        Users.ClearUserCache(user);
                    }
                    new MemberDao().UpdateUserStatistics(order.UserId, order.RefundAmount, true);
                    dao.UpdateRefundOrderStock(order.OrderId);
                }
                if (accept && (order.GroupBuyId > 0))
                {
                    EventLogs.WriteOperationLog(Privilege.RefundOrder, string.Format(CultureInfo.InvariantCulture, "对订单“{0}”成功的扣除违约金后退款", new object[] { order.OrderId }));
                }
                else
                {
                    EventLogs.WriteOperationLog(Privilege.RefundOrder, string.Format(CultureInfo.InvariantCulture, "对订单“{0}”成功的进行了全额退款", new object[] { order.OrderId }));
                }
            }
            return flag;
        }

        public static bool CheckReplace(string orderId, string adminRemark, bool accept)
        {
            ManagerHelper.CheckPrivilege(Privilege.OrderReplaceApply);
            if (GetOrderInfo(orderId).OrderStatus != OrderStatus.ApplyForReplacement)
            {
                return false;
            }
            return new ReplaceDao().CheckReplace(orderId, adminRemark, accept);
        }

        public static bool CheckReturn(OrderInfo order, string Operator, decimal refundMoney, string adminRemark, int refundType, bool accept)
        {
            ManagerHelper.CheckPrivilege(Privilege.OrderReturnsApply);
            if (order.OrderStatus != OrderStatus.ApplyForReturns)
            {
                return false;
            }
            bool flag = new ReturnDao().CheckReturn(order.OrderId, Operator, refundMoney, adminRemark, refundType, accept);
            if (flag)
            {
                if (accept)
                {
                    order.RefundAmount = refundMoney;
                    IUser user = Users.GetUser(order.UserId, false);
                    if ((user != null) && (user.UserRole == UserRole.Member))
                    {
                        ReducedPoint(order, user as Member);
                        ReduceDeduct(order.OrderId, order.RefundAmount, user as Member);
                        Users.ClearUserCache(user);
                    }
                    new MemberDao().UpdateUserStatistics(order.UserId, order.RefundAmount, false);
                }
                EventLogs.WriteOperationLog(Privilege.RefundOrder, string.Format(CultureInfo.InvariantCulture, "对订单“{0}”成功的进行了退货", new object[] { order.OrderId }));
            }
            return flag;
        }

        public static bool ClearOrderGifts(OrderInfo order)
        {
            bool flag;
            ManagerHelper.CheckPrivilege(Privilege.EditOrders);
            using (DbConnection connection = DatabaseFactory.CreateDatabase().CreateConnection())
            {
                connection.Open();
                DbTransaction dbTran = connection.BeginTransaction();
                try
                {
                    order.Gifts.Clear();
                    if (!new OrderGiftDao().ClearOrderGifts(order.OrderId, dbTran))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    if (!new OrderDao().UpdateOrder(order, dbTran))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    dbTran.Commit();
                    flag = true;
                }
                catch
                {
                    dbTran.Rollback();
                    flag = false;
                }
                finally
                {
                    connection.Close();
                }
            }
            if (flag)
            {
                EventLogs.WriteOperationLog(Privilege.EditOrders, string.Format(CultureInfo.InvariantCulture, "清空了订单号为\"{0}\"的订单礼品", new object[] { order.OrderId }));
            }
            return flag;
        }

        public static bool CloseTransaction(OrderInfo order)
        {
            ManagerHelper.CheckPrivilege(Privilege.EditOrders);
            if (order.CheckAction(OrderActions.SELLER_CLOSE))
            {
                order.OrderStatus = OrderStatus.Closed;
                bool flag = new OrderDao().UpdateOrder(order, null);
                if (flag)
                {
                    EventLogs.WriteOperationLog(Privilege.EditOrders, string.Format(CultureInfo.InvariantCulture, "关闭了订单“{0}”", new object[] { order.OrderId }));
                }
                return flag;
            }
            return false;
        }

        public static bool ConfirmOrderFinish(OrderInfo order)
        {
            ManagerHelper.CheckPrivilege(Privilege.EditOrders);
            bool flag = false;
            if (order.CheckAction(OrderActions.SELLER_FINISH_TRADE))
            {
                order.OrderStatus = OrderStatus.Finished;
                order.FinishDate = DateTime.Now;
                flag = new OrderDao().UpdateOrder(order, null);
                if (flag)
                {
                    EventLogs.WriteOperationLog(Privilege.EditOrders, string.Format(CultureInfo.InvariantCulture, "完成编号为\"{0}\"的订单", new object[] { order.OrderId }));
                }
            }
            return flag;
        }

        public static bool ConfirmPay(OrderInfo order)
        {
            ManagerHelper.CheckPrivilege(Privilege.CofimOrderPay);
            bool flag = false;
            if (order.CheckAction(OrderActions.SELLER_CONFIRM_PAY))
            {
                OrderDao dao = new OrderDao();
                order.OrderStatus = OrderStatus.BuyerAlreadyPaid;
                order.PayDate = DateTime.Now;
                flag = dao.UpdateOrder(order, null);
                if (!flag)
                {
                    return flag;
                }
                dao.UpdatePayOrderStock(order.OrderId);
                ProductDao dao2 = new ProductDao();
                foreach (LineItemInfo info in order.LineItems.Values)
                {
                    ProductInfo productDetails = dao2.GetProductDetails(info.ProductId);
                    productDetails.SaleCounts += info.Quantity;
                    productDetails.ShowSaleCounts += info.Quantity;
                    dao2.UpdateProduct(productDetails, null);
                }
                UpdateUserAccount(order);
                EventLogs.WriteOperationLog(Privilege.CofimOrderPay, string.Format(CultureInfo.InvariantCulture, "确认收款编号为\"{0}\"的订单", new object[] { order.OrderId }));
            }
            return flag;
        }

        public static bool DelDebitNote(string[] noteIds, out int count)
        {
            ManagerHelper.CheckPrivilege(Privilege.DeleteOrder);
            bool flag = true;
            count = 0;
            DebitNoteDao dao = new DebitNoteDao();
            foreach (string str in noteIds)
            {
                if (!string.IsNullOrEmpty(str))
                {
                    flag &= dao.DelDebitNote(str);
                    if (flag)
                    {
                        count++;
                    }
                }
            }
            return flag;
        }

        public static bool DeleteLineItem(string sku, OrderInfo order)
        {
            bool flag;
            ManagerHelper.CheckPrivilege(Privilege.EditOrders);
            using (DbConnection connection = DatabaseFactory.CreateDatabase().CreateConnection())
            {
                connection.Open();
                DbTransaction dbTran = connection.BeginTransaction();
                try
                {
                    order.LineItems.Remove(sku);
                    if (!new LineItemDao().DeleteLineItem(sku, order.OrderId, dbTran))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    if (!new OrderDao().UpdateOrder(order, dbTran))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    dbTran.Commit();
                    flag = true;
                }
                catch
                {
                    dbTran.Rollback();
                    flag = false;
                }
                finally
                {
                    connection.Close();
                }
            }
            if (flag)
            {
                EventLogs.WriteOperationLog(Privilege.EditOrders, string.Format(CultureInfo.InvariantCulture, "删除了订单号为\"{0}\"的订单商品", new object[] { order.OrderId }));
            }
            return flag;
        }

        public static bool DeleteOrderGift(OrderInfo order, int giftId)
        {
            bool flag;
            ManagerHelper.CheckPrivilege(Privilege.EditOrders);
            using (DbConnection connection = DatabaseFactory.CreateDatabase().CreateConnection())
            {
                connection.Open();
                DbTransaction dbTran = connection.BeginTransaction();
                try
                {
                    OrderGiftDao dao = new OrderGiftDao();
                    OrderGiftInfo orderGift = dao.GetOrderGift(giftId, order.OrderId);
                    order.Gifts.Remove(orderGift);
                    if (!dao.DeleteOrderGift(order.OrderId, orderGift.GiftId, dbTran))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    if (!new OrderDao().UpdateOrder(order, dbTran))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    dbTran.Commit();
                    EventLogs.WriteOperationLog(Privilege.EditOrders, string.Format(CultureInfo.InvariantCulture, "删除了订单号为\"{0}\"的订单礼品", new object[] { order.OrderId }));
                    flag = true;
                }
                catch
                {
                    dbTran.Rollback();
                    flag = false;
                }
                finally
                {
                    connection.Close();
                }
            }
            return flag;
        }

        public static int DeleteOrders(string orderIds)
        {
            ManagerHelper.CheckPrivilege(Privilege.DeleteOrder);
            int num = new OrderDao().DeleteOrders(orderIds);
            if (num > 0)
            {
                EventLogs.WriteOperationLog(Privilege.DeleteOrder, string.Format(CultureInfo.InvariantCulture, "删除了编号为\"{0}\"的订单", new object[] { orderIds }));
            }
            return num;
        }

        public static bool DelRefundApply(string[] refundIds, out int count)
        {
            ManagerHelper.CheckPrivilege(Privilege.OrderRefundApply);
            bool flag = true;
            count = 0;
            RefundDao dao = new RefundDao();
            foreach (string str in refundIds)
            {
                if (!string.IsNullOrEmpty(str))
                {
                    if (dao.DelRefundApply(int.Parse(str)))
                    {
                        count++;
                    }
                    else
                    {
                        flag = false;
                    }
                }
            }
            return flag;
        }

        public static bool DelReplaceApply(string[] replaceIds, out int count)
        {
            bool flag = true;
            count = 0;
            ReplaceDao dao = new ReplaceDao();
            foreach (string str in replaceIds)
            {
                if (!string.IsNullOrEmpty(str))
                {
                    if (dao.DelReplaceApply(int.Parse(str)))
                    {
                        count++;
                    }
                    else
                    {
                        flag = false;
                    }
                }
            }
            return flag;
        }

        public static bool DelReturnsApply(string[] returnsIds, out int count)
        {
            ManagerHelper.CheckPrivilege(Privilege.OrderReturnsApply);
            bool flag = true;
            count = 0;
            ReturnDao dao = new ReturnDao();
            foreach (string str in returnsIds)
            {
                if (!string.IsNullOrEmpty(str))
                {
                    if (dao.DelReturnsApply(int.Parse(str)))
                    {
                        count++;
                    }
                    else
                    {
                        flag = false;
                    }
                }
            }
            return flag;
        }

        public static bool DelSendNote(string[] noteIds, out int count)
        {
            ManagerHelper.CheckPrivilege(Privilege.DeleteOrder);
            bool flag = true;
            count = 0;
            SendNoteDao dao = new SendNoteDao();
            foreach (string str in noteIds)
            {
                if (!string.IsNullOrEmpty(str))
                {
                    flag &= dao.DelSendNote(str);
                    if (flag)
                    {
                        count++;
                    }
                }
            }
            return flag;
        }

        public static DbQueryResult GetAllDebitNote(DebitNoteQuery query)
        {
            return new DebitNoteDao().GetAllDebitNote(query);
        }

        public static DbQueryResult GetAllSendNote(RefundApplyQuery query)
        {
            return new SendNoteDao().GetAllSendNote(query);
        }

        private static string getEMSLastNum(string emsno)
        {
            List<char> list = emsno.ToList<char>();
            char ch = list[2];
            int num = int.Parse(ch.ToString()) * 8;
            ch = list[3];
            num += int.Parse(ch.ToString()) * 6;
            ch = list[4];
            num += int.Parse(ch.ToString()) * 4;
            ch = list[5];
            num += int.Parse(ch.ToString()) * 2;
            ch = list[6];
            num += int.Parse(ch.ToString()) * 3;
            ch = list[7];
            num += int.Parse(ch.ToString()) * 5;
            ch = list[8];
            num += int.Parse(ch.ToString()) * 9;
            ch = list[9];
            num += int.Parse(ch.ToString()) * 7;
            num = 11 - (num % 11);
            if (num == 10)
            {
                num = 0;
            }
            else if (num == 11)
            {
                num = 5;
            }
            return num.ToString();
        }

        private static string getEMSNext(string emsno)
        {
            long num = Convert.ToInt64(emsno.Substring(2, 8));
            if (num < 0x5f5e0ffL)
            {
                num += 1L;
            }
            string str = num.ToString().PadLeft(8, '0');
            string str2 = emsno.Substring(0, 2) + str + emsno.Substring(10, 1);
            return (emsno.Substring(0, 2) + str + getEMSLastNum(str2) + emsno.Substring(11, 2));
        }

        public static IList<GiftInfo> GetGiftList(GiftQuery query)
        {
            return new OrderGiftDao().GetGiftList(query);
        }

        public static DbQueryResult GetGifts(GiftQuery query)
        {
            return new OrderGiftDao().GetGifts(query);
        }

        private static string GetNextExpress(string ExpressCom, string strno)
        {
            switch (ExpressCom.ToLower())
            {
                case "ems":
                    return getEMSNext(strno);

                case "顺丰快递":
                    return getSFNext(strno);

                case "宅急送":
                    return getZJSNext(strno);
            }
            long num = long.Parse(strno) + 1L;
            return num.ToString();
        }

        public static DbQueryResult GetOrderGifts(OrderGiftQuery query)
        {
            return new OrderGiftDao().GetOrderGifts(query);
        }

        public static DataSet GetOrderGoods(string orderIds)
        {
            return new OrderDao().GetOrderGoods(orderIds);
        }

        public static OrderInfo GetOrderInfo(string orderId)
        {
            return new OrderDao().GetOrderInfo(orderId);
        }

        public static DbQueryResult GetOrders(OrderQuery query)
        {
            return new OrderDao().GetOrders(query);
        }

        public static DataSet GetOrdersAndLines(string orderIds)
        {
            return new OrderDao().GetOrdersAndLines(orderIds);
        }

        public static DataSet GetProductGoods(string orderIds)
        {
            return new OrderDao().GetProductGoods(orderIds);
        }

        public static DbQueryResult GetRefundApplys(RefundApplyQuery query)
        {
            return new RefundDao().GetRefundApplys(query);
        }

        public static void GetRefundType(string orderId, out int refundType, out string remark)
        {
            new RefundDao().GetRefundType(orderId, out refundType, out remark);
        }

        public static void GetRefundTypeFromReturn(string orderId, out int refundType, out string remark)
        {
            new ReturnDao().GetRefundTypeFromReturn(orderId, out refundType, out remark);
        }

        public static DbQueryResult GetReplaceApplys(ReplaceApplyQuery query)
        {
            return new ReplaceDao().GetReplaceApplys(query);
        }

        public static string GetReplaceComments(string orderId)
        {
            return new ReplaceDao().GetReplaceComments(orderId);
        }

        public static DbQueryResult GetReturnsApplys(ReturnsApplyQuery query)
        {
            return new ReturnDao().GetReturnsApplys(query);
        }

        public static DataTable GetSendGoodsOrders(string orderIds)
        {
            return new OrderDao().GetSendGoodsOrders(orderIds);
        }

        private static string getSFNext(string sfno)
        {
            int[] numArray = new int[12];
            int[] numArray2 = new int[12];
            List<char> list = sfno.ToList<char>();
            string str = sfno.Substring(0, 11);
            string source = string.Empty;
            if (sfno.Substring(0, 1) == "0")
            {
                long num2 = Convert.ToInt64(str) + 1L;
                source = "0" + num2.ToString();
            }
            else
            {
                source = (Convert.ToInt64(str) + 1L).ToString();
            }
            int index = 0;
            while (index < 12)
            {
                char ch = list[index];
                numArray[index] = int.Parse(ch.ToString());
                index++;
            }
            List<char> list2 = source.ToList<char>();
            for (index = 0; index < 11; index++)
            {
                numArray2[index] = int.Parse(source[index].ToString());
            }
            if (((numArray2[8] - numArray[8]) == 1) && ((numArray[8] % 2) == 1))
            {
                if ((numArray[11] - 8) >= 0)
                {
                    numArray2[11] = numArray[11] - 8;
                }
                else
                {
                    numArray2[11] = (numArray[11] - 8) + 10;
                }
            }
            else if (((numArray2[8] - numArray[8]) == 1) && ((numArray[8] % 2) == 0))
            {
                if ((numArray[11] - 7) >= 0)
                {
                    numArray2[11] = numArray[11] - 7;
                }
                else
                {
                    numArray2[11] = (numArray[11] - 7) + 10;
                }
            }
            else if (((numArray[9] == 3) || (numArray[9] == 6)) && (numArray[10] == 9))
            {
                if ((numArray[11] - 5) >= 0)
                {
                    numArray2[11] = numArray[11] - 5;
                }
                else
                {
                    numArray2[11] = (numArray[11] - 5) + 10;
                }
            }
            else if (numArray[10] == 9)
            {
                if ((numArray[11] - 4) >= 0)
                {
                    numArray2[11] = numArray[11] - 4;
                }
                else
                {
                    numArray2[11] = (numArray[11] - 4) + 10;
                }
            }
            else if ((numArray[11] - 1) >= 0)
            {
                numArray2[11] = numArray[11] - 1;
            }
            else
            {
                numArray2[11] = (numArray[11] - 1) + 10;
            }
            return (source + numArray2[11].ToString());
        }

        public static int GetSkuStock(string skuId)
        {
            return new SkuDao().GetSkuItem(skuId).Stock;
        }

        public static DataSet GetTradeOrders(string orderId)
        {
            return new OrderDao().GetTradeOrders(orderId);
        }

        public static DataSet GetTradeOrders(OrderQuery query, out int records)
        {
            return new OrderDao().GetTradeOrders(query, out records);
        }

        private static string getZJSNext(string zjsno)
        {
            long num = Convert.ToInt64(zjsno) + 11L;
            if ((num % 10L) > 6L)
            {
                num -= 7L;
            }
            return num.ToString().PadLeft(zjsno.Length, '0');
        }

        public static bool MondifyAddress(OrderInfo order)
        {
            ManagerHelper.CheckPrivilege(Privilege.EditOrders);
            if (order.CheckAction(OrderActions.MASTER_SELLER_MODIFY_DELIVER_ADDRESS))
            {
                bool flag = new OrderDao().UpdateOrder(order, null);
                if (flag)
                {
                    EventLogs.WriteOperationLog(Privilege.EditOrders, string.Format(CultureInfo.InvariantCulture, "修改了订单“{0}”的收货地址", new object[] { order.OrderId }));
                }
                return flag;
            }
            return false;
        }

        private static void ReduceDeduct(string orderId, decimal refundAmount, Member member)
        {
            int referralDeduct = HiContext.Current.SiteSettings.ReferralDeduct;
            if (((referralDeduct > 0) && member.ReferralUserId.HasValue) && (member.ReferralUserId.Value > 0))
            {
                IUser user = Users.GetUser(member.ReferralUserId.Value, false);
                if ((user != null) && (user.UserRole == UserRole.Member))
                {
                    Member member2 = user as Member;
                    if ((member.ParentUserId == member2.ParentUserId) && member2.IsOpenBalance)
                    {
                        decimal num2 = member2.Balance - ((refundAmount * referralDeduct) / 100M);
                        BalanceDetailInfo balanceDetails = new BalanceDetailInfo {
                            UserId = member2.UserId,
                            UserName = member2.Username,
                            TradeDate = DateTime.Now,
                            TradeType = TradeTypes.ReferralDeduct,
                            Expenses = new decimal?((refundAmount * referralDeduct) / 100M),
                            Balance = num2,
                            Remark = string.Format("退回提成因为{0}的订单{1}已退款", member.Username, orderId)
                        };
                        new BalanceDetailDao().InsertBalanceDetail(balanceDetails);
                    }
                }
            }
        }

        private static void ReducedPoint(OrderInfo order, Member member)
        {
            PointDetailInfo pointDetailInfo = new PointDetailInfo();
            pointDetailInfo.OrderId = order.OrderId;
            pointDetailInfo.UserId = member.UserId;
            pointDetailInfo.TradeDate = DateTime.Now;
            pointDetailInfo.TradeType = PointTradeType.Refund;
            pointDetailInfo.Reduced = new int?(order.Points);
            pointDetailInfo.Points = member.Points - pointDetailInfo.Reduced.Value;
            new PointDetailDao().AddPointDetail(pointDetailInfo);
        }

        public static bool SaveDebitNote(DebitNoteInfo note)
        {
            return new DebitNoteDao().SaveDebitNote(note);
        }

        public static bool SaveRemark(OrderInfo order)
        {
            ManagerHelper.CheckPrivilege(Privilege.RemarkOrder);
            bool flag = new OrderDao().UpdateOrder(order, null);
            if (flag)
            {
                EventLogs.WriteOperationLog(Privilege.RemarkOrder, string.Format(CultureInfo.InvariantCulture, "对订单“{0}”进行了备注", new object[] { order.OrderId }));
            }
            return flag;
        }

        public static bool SaveSendNote(SendNoteInfo note)
        {
            return new SendNoteDao().SaveSendNote(note);
        }

        public static bool SendGoods(OrderInfo order)
        {
            ManagerHelper.CheckPrivilege(Privilege.OrderSendGoods);
            bool flag = false;
            if (order.CheckAction(OrderActions.SELLER_SEND_GOODS))
            {
                OrderDao dao = new OrderDao();
                order.OrderStatus = OrderStatus.SellerAlreadySent;
                order.ShippingDate = DateTime.Now;
                flag = dao.UpdateOrder(order, null);
                if (!flag)
                {
                    return flag;
                }
                if (order.Gateway.ToLower() == "hishop.plugins.payment.podrequest")
                {
                    dao.UpdatePayOrderStock(order.OrderId);
                    foreach (LineItemInfo info in order.LineItems.Values)
                    {
                        ProductDao dao2 = new ProductDao();
                        ProductInfo productDetails = dao2.GetProductDetails(info.ProductId);
                        productDetails.SaleCounts += info.Quantity;
                        productDetails.ShowSaleCounts += info.Quantity;
                        dao2.UpdateProduct(productDetails, null);
                    }
                    UpdateUserAccount(order);
                }
                EventLogs.WriteOperationLog(Privilege.OrderSendGoods, string.Format(CultureInfo.InvariantCulture, "发货编号为\"{0}\"的订单", new object[] { order.OrderId }));
            }
            return flag;
        }

        public static bool SetOrderExpressComputerpe(string orderIds, string expressCompanyName, string expressCompanyAbb)
        {
            return new OrderDao().SetOrderExpressComputerpe(orderIds, expressCompanyName, expressCompanyAbb);
        }

        public static void SetOrderPrinted(string[] orderIds, bool isPrinted)
        {
            OrderDao dao = new OrderDao();
            foreach (string str in orderIds)
            {
                OrderInfo orderInfo = dao.GetOrderInfo(str);
                orderInfo.IsPrinted = true;
                dao.UpdateOrder(orderInfo, null);
            }
        }

        public static bool SetOrderShipNumber(string orderId, string startNumber)
        {
            OrderDao dao = new OrderDao();
            OrderInfo orderInfo = dao.GetOrderInfo(orderId);
            orderInfo.ShipOrderNumber = startNumber;
            return dao.UpdateOrder(orderInfo, null);
        }

        public static void SetOrderShipNumber(string[] orderIds, string startNumber, string ExpressCom = "")
        {
            string strno = startNumber;
            for (int i = 0; i < orderIds.Length; i++)
            {
                if (i != 0)
                {
                    strno = GetNextExpress(ExpressCom, strno);
                }
                new OrderDao().EditOrderShipNumber(orderIds[i], strno);
            }
        }

        public static bool SetOrderShippingMode(string orderIds, int realShippingModeId, string realModeName)
        {
            return new OrderDao().SetOrderShippingMode(orderIds, realShippingModeId, realModeName);
        }

        public static bool UpdateLineItem(string sku, OrderInfo order, int quantity)
        {
            bool flag;
            ManagerHelper.CheckPrivilege(Privilege.EditOrders);
            using (DbConnection connection = DatabaseFactory.CreateDatabase().CreateConnection())
            {
                connection.Open();
                DbTransaction dbTran = connection.BeginTransaction();
                try
                {
                    order.LineItems[sku].Quantity = quantity;
                    order.LineItems[sku].ShipmentQuantity = quantity;
                    order.LineItems[sku].ItemAdjustedPrice = order.LineItems[sku].ItemListPrice;
                    if (!new LineItemDao().UpdateLineItem(order.OrderId, order.LineItems[sku], dbTran))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    if (!new OrderDao().UpdateOrder(order, dbTran))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    dbTran.Commit();
                    flag = true;
                }
                catch (Exception)
                {
                    dbTran.Rollback();
                    flag = false;
                }
                finally
                {
                    connection.Close();
                }
            }
            if (flag)
            {
                EventLogs.WriteOperationLog(Privilege.EditOrders, string.Format(CultureInfo.InvariantCulture, "修改了订单号为\"{0}\"的订单商品数量", new object[] { order.OrderId }));
            }
            return flag;
        }

        public static bool UpdateOrderAmount(OrderInfo order)
        {
            ManagerHelper.CheckPrivilege(Privilege.EditOrders);
            bool flag = false;
            if (order.CheckAction(OrderActions.SELLER_MODIFY_TRADE))
            {
                flag = new OrderDao().UpdateOrder(order, null);
                if (flag)
                {
                    EventLogs.WriteOperationLog(Privilege.EditOrders, string.Format(CultureInfo.InvariantCulture, "修改了编号为\"{0}\"订单的金额", new object[] { order.OrderId }));
                }
            }
            return flag;
        }

        public static bool UpdateOrderPaymentType(OrderInfo order)
        {
            ManagerHelper.CheckPrivilege(Privilege.EditOrders);
            if (order.CheckAction(OrderActions.MASTER_SELLER_MODIFY_PAYMENT_MODE))
            {
                bool flag = new OrderDao().UpdateOrder(order, null);
                if (flag)
                {
                    EventLogs.WriteOperationLog(Privilege.EditOrders, string.Format(CultureInfo.InvariantCulture, "修改了订单“{0}”的支付方式", new object[] { order.OrderId }));
                }
                return flag;
            }
            return false;
        }

        public static bool UpdateOrderShippingMode(OrderInfo order)
        {
            ManagerHelper.CheckPrivilege(Privilege.EditOrders);
            if (order.CheckAction(OrderActions.MASTER_SELLER_MODIFY_SHIPPING_MODE))
            {
                bool flag = new OrderDao().UpdateOrder(order, null);
                if (flag)
                {
                    EventLogs.WriteOperationLog(Privilege.EditOrders, string.Format(CultureInfo.InvariantCulture, "修改了订单“{0}”的配送方式", new object[] { order.OrderId }));
                }
                return flag;
            }
            return false;
        }

        private static void UpdateUserAccount(OrderInfo order)
        {
            int userId = order.UserId;
            if (userId == 0x44c)
            {
                userId = 0;
            }
            IUser user = Users.GetUser(userId, false);
            if ((user != null) && (user.UserRole == UserRole.Member))
            {
                Member member = user as Member;
                PointDetailInfo point = new PointDetailInfo {
                    OrderId = order.OrderId,
                    UserId = member.UserId,
                    TradeDate = DateTime.Now,
                    TradeType = PointTradeType.Bounty,
                    Increased = new int?(order.Points),
                    Points = order.Points + member.Points
                };
                if ((point.Points > 0x7fffffff) || (point.Points < 0))
                {
                    point.Points = 0x7fffffff;
                }
                PointDetailDao dao = new PointDetailDao();
                dao.AddPointDetail(point);
                int referralDeduct = HiContext.Current.SiteSettings.ReferralDeduct;
                if (((referralDeduct > 0) && member.ReferralUserId.HasValue) && (member.ReferralUserId.Value > 0))
                {
                    IUser user2 = Users.GetUser(member.ReferralUserId.Value, false);
                    if ((user2 != null) && (user2.UserRole == UserRole.Member))
                    {
                        Member member2 = user2 as Member;
                        if ((member.ParentUserId == member2.ParentUserId) && member2.IsOpenBalance)
                        {
                            decimal num3 = member2.Balance + ((order.GetTotal() * referralDeduct) / 100M);
                            BalanceDetailInfo balanceDetails = new BalanceDetailInfo {
                                UserId = member2.UserId,
                                UserName = member2.Username,
                                TradeDate = DateTime.Now,
                                TradeType = TradeTypes.ReferralDeduct,
                                Income = new decimal?((order.GetTotal() * referralDeduct) / 100M),
                                Balance = num3,
                                Remark = string.Format("提成来自{0}的订单{1}", order.Username, order.OrderId)
                            };
                            new BalanceDetailDao().InsertBalanceDetail(balanceDetails);
                        }
                    }
                }
                MemberDao dao2 = new MemberDao();
                dao2.UpdateMemberAccount(order.GetTotal(), member.UserId);
                int historyPoint = dao.GetHistoryPoint(member.UserId);
                dao2.ChangeMemberGrade(member.UserId, member.GradeId, historyPoint);
                Users.ClearUserCache(user);
            }
        }
    }
}

